# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html

from datetime import datetime
from peewee import *
from .items import IllustrationItem, PageItem
from .models import Illustration, Artist, DailyRank, Page


class SpixivPipeline(object):
    def process_item(self, item, spider):
        if isinstance(item, PageItem):
            self.process_page(item)
        elif isinstance(item, IllustrationItem):
            self.process_illust(item)
        return item

    def process_page(self, item):
        mode = item['mode']
        p = item['p']
        date = datetime.strptime(item['date'], '%Y%m%d').date()
        try:
            Page.create(mode=mode, p=p, date=date)
        except IntegrityError:
            pass

    def process_illust(self, item):
        illust_id = item['illust_id']
        title = item['title']
        url = item['url']
        user_id = item['user_id']
        user_name = item['user_name']
        illust_upload_timestamp = item['illust_upload_timestamp']
        rank = item['rank']
        illust_page_count = item['illust_page_count']
        date = item['date']

        # Artist
        try:
            artist = Artist.get(Artist.pixiv_id == user_id)
        except DoesNotExist:
            artist = Artist.create(pixiv_id=user_id, name=user_name)

        # illustration
        try:
            illust = Illustration.get(Illustration.illust_id == illust_id)
        except DoesNotExist:
            illust = Illustration.create(illust_id=illust_id, title=title, url=url,
                                         artist=artist, upload_timestamp=illust_upload_timestamp,
                                         page_count=illust_page_count)
        # daily rank
        try:
            DailyRank.create(illustration=illust, rank=rank, date=date)
        except IntegrityError:
            pass